package com.itheima.aspect;

import com.itheima.aspect.annotation.OperLog;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomExpection;
import com.itheima.pojo.OperationLog;
import com.itheima.service.OperationLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.TimerTask;

@Component
@Aspect
public class OperationAspect {
    @Pointcut("@annotation(com.itheima.aspect.annotation.OperLog)")
    private void operationMethod(){}


    @Autowired
    private OperationLogService operationLogService;


    @Around("operationMethod()")
    public Object operatationLogHandler(ProceedingJoinPoint pjp){
        OperationLog operationLog = new OperationLog();

        //获取目标方法
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        //获取目标方法上的注解
        OperLog annotation = method.getAnnotation(OperLog.class);
        //获取注解属性
        String value = annotation.value();
        String username = annotation.username();

        operationLog.setAction(value);
        operationLog.setUserId(BaseContext.getCurrentId());
        Object[] args = pjp.getArgs();
        Object result = null;


        try {
            //前置增强
            result = pjp.proceed(args);//执行目标方法
//后置增强
        }catch (Throwable throwable){
            //throwable.printStackTrace();
            //异常增强
            //throw new CustomExpection("");
            operationLogService.save(operationLog);
        }finally {
            //返回后增强
            new AsyncManager().execute(new TimerTask() {
                @Override
                public void run() {
                    boolean save = operationLogService.save(operationLog);
                }
            });

        }
        return result;
    }
}
